import React from 'react'
import { useState, useEffect } from "react";
import styles from "./PendingOrderConfirmation.module.css";

interface PendingOrderConfirmation {
    id: number;
    operator: string;
    team: string;
    inventoryCode: string;
    warehouseName: string;
    differenceResults: string;
}

interface QueryParams {
    warehouse: string;
    team: string;
    inventoryCode: string;
}

const ConfirmOrderQuery = () => {
    // 定义数组对象，用于存储API返回的数据
    const [pendingorderList, setPendingorderList] = useState<PendingOrderConfirmation[]>([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
    
    // 下拉框选项
    const warehouseOptions = [
        { value: '仓库1', label: '仓库1' },
        { value: '仓库2', label: '仓库2' },
        { value: '仓库3', label: '仓库3' },
    ];
    const teamOptions = [
        { value: '团队1', label: '团队1' },
        { value: '团队2', label: '团队2' },
        { value: '团队3', label: '团队3' },
    ];
    
    // 查询条件状态
    const [queryParams, setQueryParams] = useState<QueryParams>({
        warehouse: '',
        team: '',
        inventoryCode: ''
    });

    // 获取待盘点订单数据
    const fetchPendingOrders = async (params?: QueryParams) => {
        try {
            setLoading(true);
            setError(null);
            
            // 构建查询URL
            let url = 'http://localhost:5233/api/OrderConfirmeds';
            const queryString = new URLSearchParams();
            
            if (params) {
                if (params.warehouse.trim()) {
                    queryString.append('WarehouseName', params.warehouse.trim());
                }
                if (params.team.trim()) {
                    queryString.append('Team', params.team.trim());
                }
                if (params.inventoryCode.trim()) {
                    queryString.append('InventoryCode', params.inventoryCode.trim());
                }
            }
            
            if (queryString.toString()) {
                url += '?' + queryString.toString();
            }
            
            const response = await fetch(url);
            
            if (!response.ok) {
                const errorText = await response.text();
                console.error('API错误响应:', errorText);
                throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`);
            }
            
            const data = await response.json();
            
            // 处理不同的数据格式
            let processedData: PendingOrderConfirmation[] = [];
            
            if (Array.isArray(data)) {
                // 直接是数组
                processedData = data;
            } else if (data && typeof data === 'object') {
                // 检查常见的包装格式
                if (Array.isArray(data.data)) {
                    processedData = data.data;
                } else if (Array.isArray(data.result)) {
                    processedData = data.result;
                } else if (Array.isArray(data.list)) {
                    processedData = data.list;
                } else if (Array.isArray(data.items)) {
                    processedData = data.items;
                } else {
                    console.error('未知的数据格式:', data);
                    throw new Error('API返回的数据格式不正确');
                }
            } else {
                throw new Error('API返回的数据不是有效格式');
            }
            
            setPendingorderList(processedData);
        } catch (err) {
            const errorMessage = err instanceof Error ? err.message : '获取数据失败';
            setError(errorMessage);
            console.error('获取待盘点订单失败:', err);
            
            // 如果是网络错误，提供更友好的提示
            if (err instanceof TypeError && err.message.includes('fetch')) {
                setError('网络连接失败，请检查后端服务是否运行在 http://localhost:5233');
            }
        } finally {
            setLoading(false);
        }
    };

    // 组件挂载时获取数据
    useEffect(() => {
        fetchPendingOrders();
    }, []);

    // 处理查询参数变化
    const handleInputChange = (field: keyof QueryParams, value: string) => {
        setQueryParams(prev => ({
            ...prev,
            [field]: value
        }));
    };

    // 执行查询
    const handleSearch = () => {
        fetchPendingOrders(queryParams);
    };

    // 清空查询条件
    const handleClear = () => {
        const emptyParams = { warehouse: '', team: '', inventoryCode: '' };
        setQueryParams(emptyParams);
        fetchPendingOrders();
    };



    // 加载状态
    if (loading) {
        return (
            <div className={styles.container}>
                <h3 className={styles.title}>待盘点订单确认</h3>
                <div className={styles.emptyState}>
                    <p>正在加载数据...</p>
                </div>
            </div>
        );
    }

    // 错误状态
    if (error) {
        return (
            <div className={styles.container}>
                <h3 className={styles.title}>待盘点订单确认</h3>
                <div className={styles.emptyState}>
                    <p>加载失败: {error}</p>
                    <button 
                        onClick={() => fetchPendingOrders()}
                        style={{
                            marginTop: '10px',
                            padding: '8px 16px',
                            backgroundColor: '#4CAF50',
                            color: 'white',
                            border: 'none',
                            borderRadius: '4px',
                            cursor: 'pointer'
                        }}
                    >
                        重新加载
                    </button>
                </div>
            </div>
        );
    }

    return (
        <div className={styles.container}>
            <h3 className={styles.title}>待盘点订单确认</h3>
            
            {/* 查询表单 */}
            <div className={styles.queryForm}>
                <div className={styles.queryRow}>
                    <div className={styles.queryField}>
                        <label className={styles.queryLabel}>仓库名称:</label>
                        <select
                            className={styles.queryInput}
                            value={queryParams.warehouse}
                            onChange={(e) => handleInputChange('warehouse', e.target.value)}
                        >
                            <option value="">请选择仓库</option>
                            {warehouseOptions.map(option => (
                                <option key={option.value} value={option.value}>
                                    {option.label}
                                </option>
                            ))}
                        </select>
                    </div>
                    <div className={styles.queryField}>
                        <label className={styles.queryLabel}>团队:</label>
                        <select
                            className={styles.queryInput}
                            value={queryParams.team}
                            onChange={(e) => handleInputChange('team', e.target.value)}
                        >
                            <option value="">请选择团队</option>
                            {teamOptions.map(option => (
                                <option key={option.value} value={option.value}>
                                    {option.label}
                                </option>
                            ))}
                        </select>
                    </div>
                    <div className={styles.queryField}>
                        <label className={styles.queryLabel}>盘点单号:</label>
                        <input
                            type="text"
                            className={styles.queryInput}
                            placeholder="请输入盘点单号"
                            value={queryParams.inventoryCode}
                            onChange={(e) => handleInputChange('inventoryCode', e.target.value)}
                        />
                    </div>
                    <div className={styles.queryButtons}>
                        <button 
                            className={`${styles.queryButton} ${styles.searchButton}`}
                            onClick={handleSearch}
                        >
                            查询
                        </button>
                        <button 
                            className={`${styles.queryButton} ${styles.clearButton}`}
                            onClick={handleClear}
                        >
                            清空
                        </button>

                    </div>
                </div>
            </div>

            {!Array.isArray(pendingorderList) || pendingorderList.length === 0 ? (
                <div className={styles.emptyState}>
                    <p>{!Array.isArray(pendingorderList) ? '数据格式错误' : '暂无待盘点订单'}</p>
                </div>
            ) : (
                <div className={styles.tableContainer}>
                    <table className={styles.table}>
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>操作员</th>
                                <th>团队</th>
                                <th>盘点单号</th>
                                <th>仓库名称</th>
                                <th>差异结果</th>
                            </tr>
                        </thead>
                        <tbody>
                            {pendingorderList.map((product) => (
                                <tr key={product.id}>
                                    <td>{product.id}</td>
                                    <td>{product.operator}</td>
                                    <td>{product.team}</td>
                                    <td>{product.inventoryCode}</td>
                                    <td>{product.warehouseName}</td>
                                    <td>{product.differenceResults}</td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            )}
        </div>
    );
}

export default ConfirmOrderQuery;